<template>  
  <div class="dashboard">  
    <!-- 时间筛选区域 -->  
    <div class="filter-section">  
      <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">  
        <el-radio-button label="week">本周</el-radio-button>  
        <el-radio-button label="month">本月</el-radio-button>  
        <el-radio-button label="year">本年</el-radio-button>  
        <el-radio-button label="all">全部</el-radio-button>  
      </el-radio-group>  
      
      <el-date-picker  
        v-model="dateRange"  
        type="daterange"  
        range-separator="至"  
        start-placeholder="开始日期"  
        end-placeholder="结束日期"  
        @change="handleDateRangeChange"  
        style="margin-left: 15px;"  
      ></el-date-picker>  

      <el-select  
        v-model="selectedDepartment"  
        placeholder="选择部门/人员"  
        style="margin-left: 15px; width: 200px;"  
        @change="handleDepartmentChange"  
      >  
        <el-option  
          v-for="dept in departments"  
          :key="dept.id"  
          :label="dept.name"  
          :value="dept.id"  
        ></el-option>  
      </el-select>  
    </div>  

    <!-- 数据统计卡片 -->  
    <el-row :gutter="20" class="stat-cards">  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">已完成产值</div>  
          <div class="stat-value">{{ formatNumber(statistics.completedValue) }}</div>  
          <!-- 新增在线产值和污水产值，保持在同一行显示 -->  
          <div style="font-size: 12px; color: #606266; display: inline;">在线产值: {{ formatNumber(statistics.onlineOutputValue) }}</div>  
          <div style="font-size: 12px; color: #606266; display: inline; margin-left: 10px;">污水产值: {{ formatNumber(statistics.sewageOutputValue) }}</div>  
        </el-card>  
      </el-col>  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">回款额</div>  
          <div class="stat-value">{{ formatNumber(statistics.paymentAmount) }}</div>  
        </el-card>  
      </el-col>  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">回款单数</div>  
          <div class="stat-value">{{ statistics.paymentCount }}</div>  
        </el-card>  
      </el-col>  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">本月签单量</div>  
          <div class="stat-value">{{ statistics.monthlyOrders }}</div>  
        </el-card>  
      </el-col>  
    </el-row>  

    <el-row :gutter="20" class="stat-cards">  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">合同数量</div>  
          <div class="stat-value">{{ statistics.contractCount }}</div>  
        </el-card>  
      </el-col>  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">未回款金额</div>  
          <div class="stat-value">{{ formatNumber(statistics.unpaidAmount) }}</div>  
          <!-- 新增本月和陈欠，保持在同一行显示 -->  
          <div style="font-size: 12px; color: #606266; display: inline;">本月: {{ formatNumber(statistics.thisMonthNoPay ) }}</div>  
          <div style="font-size: 12px; color: #606266; display: inline; margin-left: 10px;">陈欠: {{ formatNumber(statistics.chenQianPay ) }}</div>  
        </el-card>  
      </el-col>  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">成本费用</div>  
          <div class="stat-value">{{ formatNumber(statistics.costAmount) }}</div>  
        </el-card>  
      </el-col>  
      <el-col :span="6">  
        <el-card shadow="hover">  
          <div class="stat-title">新签订金额</div>  
          <div class="stat-value">{{ formatNumber(statistics.newContractAmount) }}</div>  
        </el-card>  
      </el-col>  
    </el-row>  

    <!-- 图表区域 -->  
    <el-row :gutter="20" class="chart-section">  
      <el-col :span="12">  
        <el-card shadow="hover">  
          <div slot="header">成单比分析</div>  
          <div ref="orderRatioChart" style="height: 300px;"></div>  
        </el-card>  
      </el-col>  
      <el-col :span="12">  
        <el-card shadow="hover">  
          <div slot="header">客户状态分析</div>  
          <div ref="customerStatusChart" style="height: 300px;"></div>  
        </el-card>  
      </el-col>  
    </el-row>  

    <el-row :gutter="20" class="chart-section">  
      <el-col :span="12">  
        <el-card shadow="hover">  
          <div slot="header">业绩分析</div>  
          <div ref="performanceChart" style="height: 300px;"></div>  
        </el-card>  
      </el-col>  
      <el-col :span="12">  
        <el-card shadow="hover">  
          <div slot="header">成本分析</div>  
          <div ref="costAnalysisChart" style="height: 300px;"></div>  
        </el-card>  
      </el-col>  
    </el-row>  
  </div>  
</template>  

<script>  
import * as echarts from 'echarts'  
import {getStatistics} from "@/api/monitor/statistics"; 

export default {  
  name: 'StatsDashboard',  
  
  data() {  
    return {  
      timeRange: 'month',  
      dateRange: [],  
      selectedDepartment: '',  
      departments: [  
        { id: 1, name: '销售部' },  
        { id: 2, name: '技术部' },  
        { id: 3, name: '客服部' }  
      ],  
      statistics: {  
        completedValue: 873528,  
        paymentAmount: 671800,  
        paymentCount: 747,  
        monthlyOrders: 3,  
        contractCount: 117,  
        unpaidAmount: 324826,  
        costAmount: 24532,  
        newContractAmount: 24532,
        onlineOutputValue : 8888,
        sewageOutputValue : 7777,
        thisMonthNoPay : 6666,
        chenQianPay : 5555

      },  
      charts: {  
        orderRatio: null,  
        customerStatus: null,  
        performance: null,  
        costAnalysis: null  
      }  
    }  
  },  

  mounted() {  
    this.initCharts() ; 
    this.fetchData() ;
    this.getStatistics('month');
  },  

  methods: {  
    getStatistics(type){
      getStatistics(type).then(response => {  
        this.statistics = response
        console.log(response) 
      });
    },
    formatNumber(num) {  
      return num.toLocaleString()  
    },  

    handleTimeRangeChange(value) {  
      console.log(value);
      this.timeRange = value ;
    },  

    handleDateRangeChange(value) {  
      this.fetchData()  ;
      this.getStatistics(value);
    },  

    handleDepartmentChange(value) {  
      this.fetchData()  
    },  

    async fetchData() {  
      // 模拟API调用  
      await this.fetchStatistics()  
      await this.fetchChartData()  
    },  

    async fetchStatistics() {  
      // 模拟获取统计数据  
      // const res = await api.getStatistics({  
      //   timeRange: this.timeRange,  
      //   dateRange: this.dateRange,  
      //   department: this.selectedDepartment  
      // })  
      // this.statistics = res.data  
    },  

    async fetchChartData() {  
      // 模拟获取图表数据并更新  
      this.updateOrderRatioChart()  
      this.updateCustomerStatusChart()  
      this.updatePerformanceChart()  
      this.updateCostAnalysisChart()  
    },  

    initCharts() {  
      this.charts.orderRatio = echarts.init(this.$refs.orderRatioChart)  
      this.charts.customerStatus = echarts.init(this.$refs.customerStatusChart)  
      this.charts.performance = echarts.init(this.$refs.performanceChart)  
      this.charts.costAnalysis = echarts.init(this.$refs.costAnalysisChart)  

      window.addEventListener('resize', this.handleResize)  
    },  

    handleResize() {  
      Object.values(this.charts).forEach(chart => {  
        chart && chart.resize()  
      })  
    },  

    updateOrderRatioChart() {  
      const option = {  
        tooltip: { trigger: 'item' },  
        legend: { orient: 'horizontal', bottom: 0 },  
        series: [{  
          type: 'pie',  
          radius: '70%',  
          data: [  
            { value: 2, name: '已成单' },  
            { value: 0, name: '未成单' }  
          ],  
          emphasis: {  
            itemStyle: {  
              shadowBlur: 10,  
              shadowOffsetX: 0,  
              shadowColor: 'rgba(0, 0, 0, 0.5)'  
            }  
          }  
        }]  
      }  
      this.charts.orderRatio.setOption(option)  
    },  

    updateCustomerStatusChart() {  
      const option = {  
        tooltip: { trigger: 'item' },  
        legend: { orient: 'horizontal', bottom: 0 },  
        series: [{  
          type: 'pie',  
          radius: '70%',  
          data: [  
            { value: 110, name: '未合作' },  
            { value: 124, name: '洽谈中' },  
            { value: 116, name: '已合作' }  
          ],  
          emphasis: {  
            itemStyle: {  
              shadowBlur: 10,  
              shadowOffsetX: 0,  
              shadowColor: 'rgba(0, 0, 0, 0.5)'  
            }  
          }  
        }]  
      }  
      this.charts.customerStatus.setOption(option)  
    },  

    updatePerformanceChart() {  
      const option = {  
        tooltip: { trigger: 'axis' },  
        xAxis: {  
          type: 'time',  
          boundaryGap: false  
        },  
        yAxis: { type: 'value' },  
        series: [{  
          name: '业绩',  
          type: 'line',  
          smooth: true,  
          data: this.generateTimeData()  
        }]  
      }  
      this.charts.performance.setOption(option)  
    },  

    updateCostAnalysisChart() {  
      const option = {  
        tooltip: { trigger: 'axis' },  
        xAxis: {  
          type: 'time',  
          boundaryGap: false  
        },  
        yAxis: { type: 'value' },  
        series: [{  
          name: '成本',  
          type: 'line',  
          smooth: true,  
          data: this.generateTimeData()  
        }]  
      }  
      this.charts.costAnalysis.setOption(option)  
    },  

    generateTimeData() {  
      const data = []  
      const startTime = new Date('2022-01-01').getTime()  
      const endTime = new Date().getTime()  
      
      for (let time = startTime; time <= endTime; time += 86400000) {  
        data.push([  
          new Date(time),  
          Math.round(Math.random() * 10)  
        ])  
      }  
      return data  
    },  

    beforeDestroy() {  
      window.removeEventListener('resize', this.handleResize)  
      Object.values(this.charts).forEach(chart => {  
        chart && chart.dispose()  
      })  
    }  
  }  
}  
</script>  

<style scoped>  
.dashboard {  
  padding: 20px;  
}  

.filter-section {  
  margin-bottom: 20px;  
  background: #fff;  
  padding: 15px;  
  border-radius: 4px;  
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);  
}  

.stat-cards {  
  margin-bottom: 20px;  
}  

.stat-cards .el-card {  
  margin-bottom: 20px;  
}  

.stat-title {  
  font-size: 14px;  
  color: #606266;  
  margin-bottom: 10px;  
}  

.stat-value {  
  font-size: 24px;  
  font-weight: bold;  
  color: #303133;  
}  

.chart-section {  
  margin-bottom: 20px;  
}  

.chart-section .el-card {  
  margin-bottom: 20px;  
}  
</style>